﻿namespace TestTool.HttpTransport
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.ServiceModel.Channels;
    using TestTool.HttpTransport.Interfaces;

    public class HttpTransportBindingElement : TransportBindingElement
    {
        private List<IChannelController> _controllers;

        public HttpTransportBindingElement(IEnumerable<IChannelController> controllers)
        {
            this._controllers = new List<IChannelController>();
            if (controllers != null)
            {
                this._controllers.AddRange(controllers);
            }
        }

        protected HttpTransportBindingElement(TestTool.HttpTransport.HttpTransportBindingElement other) : base(other)
        {
            this._controllers = other._controllers;
        }

        public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            return (IChannelFactory<TChannel>) new HttpChannelFactory(this, context);
        }

        public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context) //where TChannel: class, IChannel
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (!this.CanBuildChannelListener<TChannel>(context))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Unsupported channel type: {0}.", new object[] { typeof(TChannel).Name }));
            }
            return (IChannelListener<TChannel>) new HttpRequestChannelListener(this, context);
        }

        public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
        {
            return (typeof(TChannel) == typeof(IRequestChannel));
        }

        public override bool CanBuildChannelListener<TChannel>(BindingContext context) //where TChannel: class, IChannel
        {
            return (typeof(TChannel) == typeof(IReplyChannel));
        }

        public override BindingElement Clone()
        {
            return new TestTool.HttpTransport.HttpTransportBindingElement(this);
        }

        public override T GetProperty<T>(BindingContext context) //where T: class
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            return context.GetInnerProperty<T>();
        }

        public List<IChannelController> Controllers
        {
            get
            {
                return this._controllers;
            }
        }

        public override string Scheme
        {
            get
            {
                return "http";
            }
        }
    }
}

